


#include "swdata.h"
#include "heap_4.h"


/**
 * @fn      
 * @brief  
 * @param   
 * @return  */
void SwDataInit(SwDataDef *pxSwData , uint16 usNbItem)
{
	/* is initialize. */
	pxSwData->bIsInit = false;

	/* malloc space. */
	pxSwData->puDataBuffer = osal_mem_alloc(usNbItem * sizeof(uint16));

	/* Write position. */
	pxSwData->usWrPtr = 0;

	/* If buffer is not empty. */
	if (pxSwData->puDataBuffer != NULL){
		pxSwData->usNbItem = usNbItem;
		LOG("%s:malloc ok,space %d\r\n" , __FUNCTION__ , usNbItem * sizeof(uint16) );
	}else {
		pxSwData->usNbItem = 0;
		LOG("%s:malloc err\r\n", __FUNCTION__ );
	}
}
	
/**
 * @fn      
 * @brief  
 * @param   
 * @return  */
void prvDataFill(SwDataDef *pxSwData , uint16 usFillVal)
{
	for (uint16 i = 0; i < pxSwData->usNbItem; i++) {
		pxSwData->puDataBuffer[i] = usFillVal;
	}
	pxSwData->usWrPtr = 0;
}

/**
 * @fn      
 * @brief  write a value to data buffer.
 * @param  
 * @return  */
void SwDataWrite(SwDataDef *pxSwData , uint16 usVal)
{
	uint16 usWrPc = 0;

	if (pxSwData->puDataBuffer == NULL){
		return;
	}

	/* Initialize process. */
	if (pxSwData->bIsInit == false){
		prvDataFill(pxSwData, usVal);
		pxSwData->bIsInit = true;
	}else {
		/* Get write pointer position. */
		usWrPc = pxSwData->usWrPtr;

		/* Write value to buffer. */
		pxSwData->puDataBuffer[usWrPc] = usVal;

		/* Write pointer increase. */
		pxSwData->usWrPtr++;
		if (pxSwData->usWrPtr >= pxSwData->usNbItem){
			pxSwData->usWrPtr = 0;
		}
	}
}

/**
 * @fn      
 * @brief  
 * @param   
 * @return  */
void SwDataDestroy(SwDataDef *pxSwData)
{
	if (pxSwData->puDataBuffer != NULL){
		osal_mem_free(pxSwData->puDataBuffer);
	}

	memset(pxSwData, 0, sizeof(SwDataDef));
}

/**
 * @fn      
 * @brief  Get smooth window data average value.
 * @param   
 * @return  */
uint16 SwDataAvgGet(SwDataDef *pxSwData)
{
	uint32 ulSum = 0;

	if (pxSwData->bIsInit == false){
		return 0;
	}

	/* the sum. */
	for (uint16 i = 0; i < pxSwData->usNbItem; i++) {
		ulSum += pxSwData->puDataBuffer[i];
	}

	/* calculator average. */
	return (ulSum / pxSwData->usNbItem);

}












